package org.zhxy.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zhxy.model.request.LoginRequest;
import org.zhxy.model.result.Result;
import org.zhxy.service.SystemService;

import java.io.File;
import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Tag(name = "系统管理")
@RestController
@RequestMapping("/sms/system")
@RequiredArgsConstructor
public class SystemController {

    private final SystemService systemService;

    @Operation(summary = "获取图形验证码")
    @GetMapping("/getVerifiCodeImage")
    public void getCaptcha(HttpSession httpSession, HttpServletResponse response) throws IOException {
        systemService.getCaptcha(httpSession, response);
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest, HttpSession httpSession) {
        log.info("用户登录，请求参数：{}", loginRequest);

        String token = systemService.login(loginRequest, httpSession);
        log.info("用户登录，响应数据：{}", token);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map);
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/getInfo")
    public Result getInfo() {
        Map<String, Object> userInfo = systemService.getUserInfo();
        log.info("获取用户信息，响应数据：{}", userInfo);

        return Result.ok(userInfo);
    }

    @Operation(summary = "头像上传")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(@RequestPart("multipartFile") MultipartFile multipartFile) {

        // 使用UUID随机生成文件名
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        // 生成新的文件名字
        String filename = uuid.concat(multipartFile.getOriginalFilename());
        // 生成文件的保存路径(实际生产环境这里会使用真正的文件存储服务器)
        String portraitPath = "/Users/walter/Documents/Workspace/智慧校园/zhxy-back/target/classes/public/upload/".concat(filename);
        // 保存文件
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String headerImg = "upload/" + filename;
        return Result.ok(headerImg);
    }

    @Operation(summary = "更新自己的密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(@PathVariable("oldPwd") String oldPwd, @PathVariable("newPwd") String newPwd) {
        systemService.updatePwd(oldPwd, newPwd);
        return Result.ok();
    }
}
